﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyHealthByDesignWebsite.Models;
using System.Collections;

namespace MyHealthByDesignWebsite.Controllers
{
    
    /// <summary>
    /// Description:  Controller for DietAndNutrition
    ///Created:  Nov 2011
    ///Programmer:  Swathi Thopucherla
    ///pre-condition:  MyHealth information has been submitted
    ///post-condition:  Users FooDIntake is analyzed and recommendations are made.
    /// </summary>
    public class DietAndNutritionController : Controller
    {
        
        FoodDesc foodDes = new FoodDesc();
        FoodEntry foodEntry = new FoodEntry();
        UserFoodJournal userFoodJournal = new UserFoodJournal();
        HashSet<string> selectItemsDesc = new HashSet<string>();
        private FullDataSetDataContext db = new FullDataSetDataContext();
        Hashtable mealItemsTable;
        
        int UserID;
        
        //
        // GET: /DietAndNutrition/

        public ActionResult Index()
        {
            UserID = Convert.ToInt32(Request.Cookies["UserID"].Value);
            return View();
        }

        /// <summary>
        /// This method is used for all the functionality done on 'MyFoodTracker' page
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        public ActionResult MyFoodTracker(FormCollection formCollection)
        {

            
            var timeOfTheDay = formCollection["FoodTime"];
            UserID = Convert.ToInt32(Request.Cookies["UserID"].Value);
            ViewData["UserID"] = UserID;
            System.Diagnostics.Debug.Print("User ID is :- " + UserID);
            //Start of logic to calculate User's Age based of current date
            IQueryable<DateTime?> result= from m in db.Users where m.U_userID.Equals(UserID) select m.U_DOB;
            DateTime User_DOB=(DateTime)result.First();
            TimeSpan span = (DateTime.Now).Subtract(User_DOB);
            int years=(int)(span.Days)/365;
            ViewData["AGE"] = years;
            //End of Age calculation logig

            //Generating values for 'Physical Activity' dropdown on MyFoodTracker page
            var activityList = new SelectList(new[]
                                          {
                                              new {ID="A",Name="Active"},
                                              new{ID="HA",Name="Highly Active"},
                                              new{ID="MA",Name="Minimally Active"},
                                              new{ID="S",Name="Sedentary"},
                                              new{ID="SA",Name="Somewhat Active"},
                                              
                                          },
                            "ID", "Name", 1);
            ViewData["ActivityList"] = activityList;
            
            //Below condition is to check if the 'Search' button on MyFoodTracker page is clicked
            //and if clicked, then the search string is not empty.
            if (formCollection["SearchText"] != null && formCollection["SearchText"].Trim().Length >0 && formCollection["FoodDescription"]==null)
            {
                String searchText = formCollection["SearchText"];
                //Gets the list of food items which has the 'SearchText' in their 
                //food description.
                var foodDescription = foodDes.FoodDescByText(searchText).ToList();

                //Generating values for 'MealTime' dropdown on MyFoodTracker page
                var list = new SelectList(new[]
                                          {
                                              new {ID="BreakFast",Name="BreakFast"},
                                              new{ID="Morn Snack",Name="Morning Snack"},
                                              new{ID="Lunch",Name="Lunch"},
                                              new{ID="After Snack",Name="Afternoon Snack"},
                                              new{ID="Dinner",Name="Dinner"},
                                              new{ID="Even Snack",Name="Evening Snack"},
                                          },
                            "ID", "Name", 1);
                ViewData["list"] = list;

                
                //Checking if search result for 'SearchText' has any food items
                if (foodDescription.Count > 0)
                {
                    ViewData["foodDesc"] = new MultiSelectList(foodDescription, "NDB_No", "Long_Desc");
                  
                }
                
                mealItemsTable = UserFoodJournalDetails(UserID);
                ViewData["selectedFoodDesc"] = mealItemsTable;
                return View();
                
            }//If there are any food items selected from the above search result dropdown
            else if (formCollection["FoodDescription"] != null)
            {              
                //Getting the selected food items from the search 
                //result dropdown on 'MyFoodTracker' page
                var selectedItems = formCollection["FoodDescription"].Split(',');
                //Getting the MealTime of the above selected food items on 
                //'MyFoodTracker' page.
                string mealTime=formCollection["FoodTime"];
                
                //For each food item selected on the form.
                foreach (string m in selectedItems)
                {
                    userFoodJournal.U_userID = UserID;
                    userFoodJournal.NDB_No = m;
                    //Getting food description for that food item.
                    selectItemsDesc.Add(foodDes.FoodDescByNDBNo(m));
                    userFoodJournal.UFJ_mealTime = mealTime;
                    userFoodJournal.UFJ_date = DateTime.Now;
                    //Adding the selected food items to 'UserFoodJournal' table.
                    foodEntry.Create(userFoodJournal);
                }

                //Getting all the FoodItems of that user from 'UserFoodJournal' Table
                //to display on 'MyFoodTracker' page
                mealItemsTable = UserFoodJournalDetails(UserID);

                ViewData["selectedFoodDesc"] = mealItemsTable;
                
                return View();
            }//If 'Search' button is not clicked (or) a item from fooditem drop down is not selected 
            else
            {
                mealItemsTable = UserFoodJournalDetails(UserID);
                ViewData["selectedFoodDesc"] = mealItemsTable;

                //If 'Analyze' button is selected
                if (formCollection["Analyze"] != null)
                {
                    //Checking if there are any food items listed above 'Analyze' button
                    //on 'MyFoodTracker' page.
                    if(mealItemsTable!=null && mealItemsTable.Count>0)
                    {
                        //Getting all the records of that user from 'UserFoodJournal' table
                        //so that the quantity entered under 'Food Quantity' section of
                        //'MyFoodTracker' page can be updated to the DB record.
                        IEnumerable<UserFoodJournal> UserJournalDetails = foodEntry.DetailsByUserID(UserID);
                        foreach (var item in UserJournalDetails)
                        {
                            item.U_userID = UserID;
                            item.UFJ_quntity = formCollection[item.NDB_No].Trim();
                            foodEntry.Update(item);
                            
                        }
                      }
                    
                   return RedirectToAction("MyAnalyzedFoodIntake");
                   
                }

                //If 'Edit Profile' section of 'MyFoodTracker' page is updated. 
                if (formCollection["EditProfile"] != null)
                {
                    NutritionProfile nutritionProfile = new NutritionProfile();
                    nutritionProfile.U_UserID = UserID;
                    nutritionProfile.AL_activityLevelID = formCollection["ACTIVITY"];
                    string hgt = formCollection["HEIGHT"];
                    nutritionProfile.NP_heightIn = Convert.ToDecimal(hgt);
                    decimal value=(decimal)(nutritionProfile.NP_heightIn/12);
                    nutritionProfile.NP_heightFt = Math.Round(value, 2);
                    nutritionProfile.NP_weight = Convert.ToDecimal(formCollection["WEIGHT"]);
                    nutritionProfile.NP_entryDate = DateTime.Now;
                    //Insert the values of 'Edit Profile' form to 'NutritionProfile' table.
                    nutritionProfile.insertNutritionProfile(nutritionProfile);
                    
                }
                return View();
            }

            
   
        }

        /**Below method is used to get the list of 
         * fooditems that the user takes on a daily basis.
         * 
         * */
        private Hashtable UserFoodJournalDetails(int UserID)
        {
            Hashtable mealItemsTable = new Hashtable();
            //Getting all the records of that user from 'UserFoodJournal' table
            var UserJournalDetails = foodEntry.DetailsByUserID(UserID);
            //Below HashSets will have 'NDB_No'(Code for the food item)as Key,
            //Value (List<string>) will have FoodDesc and FoodQuantity of a 
            //specific food item taken by the User at specific time of the day
            HashSet<KeyValuePair<string, List<string>>> BreakFastSet = new HashSet<KeyValuePair<string, List<string>>>();
            HashSet<KeyValuePair<string, List<string>>> MornSnackSet = new HashSet<KeyValuePair<string, List<string>>>();
            HashSet<KeyValuePair<string, List<string>>> LunchSet = new HashSet<KeyValuePair<string, List<string>>>();
            HashSet<KeyValuePair<string, List<string>>> AftSnackSet = new HashSet<KeyValuePair<string, List<string>>>();
            HashSet<KeyValuePair<string, List<string>>> DinnerSet = new HashSet<KeyValuePair<string, List<string>>>();
            HashSet<KeyValuePair<string, List<string>>> EveSnackSet = new HashSet<KeyValuePair<string, List<string>>>();
           
           
           //Looping through the 'UserJournalDetails' result set to fill in
           //the HashSet with Key and Values, so that the HashTable can be used
           //For displaying information on 'MyFoodTracker' page.
           foreach (var item in UserJournalDetails)
            {
                
                if (item.UFJ_mealTime.Equals("BreakFast"))
                {
                    List<string> breakFast = new List<string>();
                    breakFast.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    breakFast.Add(item.UFJ_quntity);
                    BreakFastSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, breakFast));
                    
                }
                if (item.UFJ_mealTime.Equals("Morn Snack"))
                {
                    List<string> morSnack = new List<string>();
                    morSnack.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    morSnack.Add(item.UFJ_quntity);
                    MornSnackSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, morSnack));
                }
                if (item.UFJ_mealTime.Equals("Lunch"))
                {
                    List<string> lunch = new List<string>();
                    lunch.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    lunch.Add(item.UFJ_quntity);
                    LunchSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, lunch));
                }
                if (item.UFJ_mealTime.Equals("After Snack"))
                {
                    List<string> aftSnack = new List<string>();
                    aftSnack.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    aftSnack.Add(item.UFJ_quntity);
                    AftSnackSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, aftSnack));
                }
                if (item.UFJ_mealTime.Equals("Dinner"))
                {
                    List<string> dinner = new List<string>();
                    dinner.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    dinner.Add(item.UFJ_quntity);
                    DinnerSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, dinner));
                }
                if (item.UFJ_mealTime.Equals("Even Snack"))
                {
                    List<string> eveSnack = new List<string>();
                    eveSnack.Add(foodDes.FoodDescByNDBNo(item.NDB_No));
                    eveSnack.Add(item.UFJ_quntity);
                    EveSnackSet.Add(new KeyValuePair<string, List<string>>(item.NDB_No, eveSnack));
                }

            }

            
            mealItemsTable.Add("BreakFast", BreakFastSet);
            mealItemsTable.Add("Morn Snack", MornSnackSet);
            mealItemsTable.Add("Lunch", LunchSet);
            mealItemsTable.Add("After Snack", AftSnackSet);
            mealItemsTable.Add("Dinner", DinnerSet);
            mealItemsTable.Add("Even Snack", EveSnackSet);

            return mealItemsTable;
        }


        public ActionResult MyNutritionProfile()
        {

            ViewBag.Message = "MyNutritionProfile...";
            return View();
        }


        public ActionResult MyAnalyzedFoodIntake()
        {

            ViewBag.Message = "MyAnalyzedFoodIntake...";
            return View();
        }

    }
}
